package net;

import java.io.PrintWriter;
import java.util.Collection;

import message.CommunityStatusNotificaton;
import message.handler.StatusHandler;

import comunity.Community;
import comunity.Status;

public class Helloer implements Runnable {

	private int milliSeconds;

	public Helloer(int milliSeconds) {
		this.milliSeconds = milliSeconds;
	}

	public Helloer() {
		this(15 * 1000);
	}

	@Override
	public void run() {
		try {
			this._run();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	private void _run() throws InterruptedException {
		Community community = Community.obtainCommunity();
		
		String packetRappresentation = "";
		while (true) {
			Thread.sleep(this.milliSeconds);
			Collection<String> usernames = community.getOnlineUsers();
			for (String receiver : usernames) {
				packetRappresentation = new CommunityStatusNotificaton(
						receiver, 0, community.getCommunityFor(receiver)).toXML();
				
				if(!community.existUserSocket(receiver) || community.isUserSocketClosed(receiver)){
					this.handleOfflineUser(receiver, community);
					System.out.println("[Errore][Helloer] "+packetRappresentation);
					packetRappresentation = "";
					continue;
				}
				PrintWriter out = community.getUserPrintWriter(receiver);
				out.println(packetRappresentation);
				out.flush();
				
				System.out.println("[out] "+packetRappresentation);
			}
		}
	}
	
	private void handleOfflineUser(String offlineUser, Community community){
		community.setUserStatus(offlineUser, Status.OFFLINE);
		new Thread(new StatusHandler(offlineUser, Status.OFFLINE)).start();		
	}

}